package logic

import (
	"context"
	"fmt"
	"library/models/cache"
	"library/pkg"
	"math/rand"
	"strconv"
	"time"

	"library/library/internal/svc"
	"library/library/library"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *library.SendSmsRequest) (*library.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	get := cache.Rdb.Get(l.ctx, "sendNumber"+in.Source+in.Mobile)
	if get.Val() >= "1" {
		return nil, fmt.Errorf("每分钟只能发送一次短信")
	}

	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	fmt.Println(sms, err)

	if err != nil {
		return nil, err
	}
	if *sms.Body.Message != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}

	cache.Rdb.Set(l.ctx, "sendSms"+in.Source+in.Mobile, code, time.Minute*3)

	cache.Rdb.Incr(l.ctx, "sendNumber"+in.Source+in.Mobile)
	cache.Rdb.Expire(l.ctx, "sendNumber"+in.Source+in.Mobile, time.Minute*1)

	return &library.SendSmsResponse{}, nil
}
